from django.shortcuts import render, HttpResponse, redirect
from xadmin.models import Sites
from xadmin.forms import site
from django.views.decorators.http import require_POST, require_GET
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required

from xadmin.plugins.auditlog import add_log


@login_required
def site_list(request):
    sites = Sites.objects.filter(status=True)
    mbx = ('站点管理', )
    context = {
        'sites': sites,
        'mbx': mbx
    }
    return render(request, 'xadmin/site/list.html', context)


@login_required
def site_add(request):
    if request.method == 'GET':
        title = '站点管理'
        mbx = ('站点管理', '新建站点')
        site_form = site.SitesForm()
        context = {
            'title': title,
            'site_form': site_form,
            'mbx': mbx
        }
        return render(request, 'xadmin/site/add.html', context)
    else:
        f = site.SitesForm(request.POST, request.FILES)
        if f.is_valid():
            # newsite = f.save(commit=False)
            # newsite.logo = request.FILES["logo"]
            # newsite.save()
            f.save()
            action = '添加了站点《%s》' % (f.name)
            add_log(request, action, None)
        return redirect(site_list)


@login_required
def site_edit(request, siteid):
    site_obj = Sites.objects.get(id=siteid)
    mbx = ('站点管理', '编辑站点')
    if request.method == 'GET':
        site_form = site.SitesForm(instance=site_obj)
        context = {
            'title': site_obj.name,
            'site_form': site_form,
            'mbx': mbx
        }
        return render(request, 'xadmin/site/add.html', context)
    else:
        f = site.SitesForm(request.POST, request.FILES, instance=site_obj)
        if f.is_valid():
            f.save()
            action = '修改了站点《%s》' % (f.cleaned_data['name'])
            add_log(request, action, None)
            return redirect(site_list)
        else:
            context = {
                'title': site_obj.name,
                'site_form': f,
                'mbx': mbx
            }
            return render(request, 'xadmin/site/add.html', context)


@login_required
@require_POST
def site_del(request, siteid):
    mess = {}
    try:
        s = Sites.objects.get(id=siteid)
        s.delete()
        mess['status'] = '200'
        mess['message'] = '删除成功'
        action = '删除了站点《%s》' % (s.name)
        add_log(request, action, None)
    except Exception as e:
        mess['status'] = '500'
        mess['message'] = '删除失败'
    return JsonResponse(mess)
